package com.selfdiscipline.ui.screens.task

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.data.local.entity.TaskEntity
import com.selfdiscipline.domain.repository.TaskRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import javax.inject.Inject

@HiltViewModel
class TaskAddEditViewModel @Inject constructor(
    private val taskRepository: TaskRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(TaskAddEditUiState())
    val uiState: StateFlow<TaskAddEditUiState> = _uiState.asStateFlow()
    
    private var taskId: Long? = null
    private var isEditMode = false

    /**
     * 加载任务详情（编辑模式）
     */
    fun loadTask(id: Long) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            taskId = id
            isEditMode = true
            
            try {
                val task = taskRepository.getTaskById(id)
                if (task != null) {
                    _uiState.update { 
                        it.copy(
                            title = task.title,
                            description = task.description,
                            priority = task.priority,
                            dueDate = task.dueDate,
                            estimatedMinutes = 30,
                            isLoading = false,
                            error = null
                        )
                    }
                } else {
                    _uiState.update { 
                        it.copy(
                            isLoading = false,
                            error = "找不到该任务"
                        )
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "获取任务详情失败"
                    )
                }
            }
        }
    }

    /**
     * 保存任务
     */
    fun saveTask() {
        viewModelScope.launch {
            val state = uiState.value
            
            if (state.title.isBlank()) {
                _uiState.update { it.copy(error = "任务标题不能为空") }
                return@launch
            }
            
            try {
                val task = TaskEntity(
                    id = taskId ?: 0L,
                    title = state.title,
                    description = state.description ?: "",
                    priority = state.priority,
                    dueDate = state.dueDate,
                    createdAt = LocalDateTime.now(),
                    isCompleted = false,
                    completedAt = null
                )
                
                if (isEditMode && taskId != null) {
                    taskRepository.updateTask(task)
                } else {
                    taskRepository.insertTask(task)
                }
                
                // 重置状态
                _uiState.update {
                    TaskAddEditUiState(error = null)
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(error = e.message ?: "保存任务失败")
                }
            }
        }
    }

    /**
     * 更新标题
     */
    fun updateTitle(title: String) {
        _uiState.update { it.copy(title = title) }
    }

    /**
     * 更新描述
     */
    fun updateDescription(description: String) {
        _uiState.update { it.copy(description = description) }
    }

    /**
     * 更新优先级
     */
    fun updatePriority(priority: Int) {
        _uiState.update { it.copy(priority = priority) }
    }

    /**
     * 更新截止日期
     */
    fun updateDueDate(dueDate: LocalDateTime?) {
        _uiState.update { it.copy(dueDate = dueDate) }
    }

    /**
     * 更新预计时间（分钟）
     */
    fun updateEstimatedTime(minutes: Int) {
        _uiState.update { it.copy(estimatedMinutes = minutes) }
    }
}

data class TaskAddEditUiState(
    val title: String = "",
    val description: String? = null,
    val priority: Int = 1, // 0: 低, 1: 中, 2: 高
    val dueDate: LocalDateTime? = null,
    val estimatedMinutes: Int = 30,
    val isLoading: Boolean = false,
    val error: String? = null
) 